#include "mplayerwrapper.h"


MPlayerWrapper::MPlayerWrapper(QString home, QObject * parent) :
    QObject(parent)
{
    this->kDeadMouseHome=home;
    this->innerProcess = new QProcess(this);
    this->refreshTimer = new QTimer(this);
    //connect Signals
    this->innerProcess->setProcessChannelMode(QProcess::MergedChannels);
    connect(innerProcess,SIGNAL(readyReadStandardOutput()),this,SLOT(readyToRead()));
    connect(innerProcess,SIGNAL(readyReadStandardError()),this,SLOT(readyToReadError()));
    connect(innerProcess,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(processFinished(int, QProcess::ExitStatus)));
    connect(refreshTimer, SIGNAL(timeout()), this, SLOT(refreshPosition()));
}

void MPlayerWrapper::setEmbeeder(QWidget * w){
    this->embeeder=w;
}



MPlayerWrapper::~MPlayerWrapper(){
    innerProcess->kill();
    qDebug()<<"killing proc";
    delete innerProcess;
    delete refreshTimer;
}

void MPlayerWrapper::playVideo(QString type,QString vId){
    this->nextIdToPlay = vId;
    this->nextTypeToPlay = type;
    if(QProcess::NotRunning == innerProcess->state()){
        this->playNextVideo();
        return;
    }
    qDebug()<<"quit for the next";
    this->sendOrder("quit");
}
void MPlayerWrapper::playNextVideo(){
    //ex : mplayer -slave -quiet -wid idInnerWin -cookies -cookies-file ${COOKIE_FILE} $(youtube-dl -g --cookies ${COOKIE_FILE} $*)
    // p_args = -cookies -cookies-file ${COOKIE_FILE} $(youtube-dl -g --cookies ${COOKIE_FILE} $*)
    this->length=0;
    this->aspect=0;
    QString type = nextTypeToPlay;
    QString vId = nextIdToPlay;
    nextTypeToPlay = QString();
    nextIdToPlay = QString();
    qDebug()<<"load:" << type << " , id:"<< vId;


    qDebug()<<"launch process";
    QStringList args;
    //args << type;
    args << vId;
    args << QString::number(this->embeeder->winId());
    qDebug() << "start with" << args;
    QString cmd = kDeadMouseHome +  "/common/bin/players/" + type;
    qDebug() << "cmd: " << cmd;
    qDebug() << "args: " << args;
    innerProcess->start(cmd,args);
    qDebug() << "Process lauched";
    if (!innerProcess->waitForStarted(-1)){
         QString err = innerProcess->errorString();
         qDebug() << "Start failed:" << err;
         emit(failedToStart(err));
         return;
    }
    qDebug() << "lauched OK";

}

void MPlayerWrapper::onLaunched(){
    qDebug() << "onLauched, length:"<<length<<" ,aspect:"<<aspect;
    if(length==0){
        sendOrder("get_time_length");
        return;
    }
    int l = length;
    emit(started(l,aspect));
    this->refreshTimer->start(1500);


}

void MPlayerWrapper::refreshPosition(){
    this->sendOrder("get_time_pos"); //("get_percent_pos");
}

void MPlayerWrapper::pause(){
    if(this->refreshTimer->isActive()){
        this->refreshTimer->stop();
        this->sendOrder("pause");
        emit(pausing());
    }else{
        this->refreshTimer->start(1500);
        emit(playing()); //y a t il un temps de letence de 1500ms
    }
}

void MPlayerWrapper::relativeSeek(int seconds){
    this->sendOrder("seek " + seconds);
}


void MPlayerWrapper::readyToRead(){
    while(innerProcess->canReadLine()) {
        QString lineOut = innerProcess->readLine();
        lineOut.replace(QByteArray("'"), QByteArray(""));
        lineOut.replace(QByteArray("\""), QByteArray(""));
        lineOut.replace(QByteArray("\n"), QByteArray(""));

        //qDebug() << "readLine--"<<lineOut<<"--";
        //traitement de la sortie:


        // duration: 256 (au debut) readLine " duration: 177"
       if(lineOut.startsWith(" duration")){
            lineOut.remove(0, 11);
            this->length=lineOut.toDouble();
            qDebug()<<"length:'" << length <<"'";
       }



        //get_time_length
        //ANS_LENGTH=7501.49
        else if(lineOut.startsWith("ANS_LENGTH=")){
            int ind = lineOut.indexOf("=");
            lineOut = lineOut.mid(ind+1);
            qDebug() << "legnth--"<<lineOut<<"--";
            length = lineOut.toDouble();
            qDebug()<<"length:'" << length <<"'";
            this->onLaunched();
        }

        //get_percent_pos
        //ANS_PERCENT_POSITION=4
        else if(lineOut.startsWith("ANS_PERCENT_POSITION=")){
            lineOut.remove(0, 20);
            double percentPos = lineOut.toDouble();
            percentPos = percentPos / 100.0;
            emit(positionNofify(percentPos));
        }

        //get_time_pos
        //ANS_TIME_POSITION=106.2
        else if(lineOut.startsWith("ANS_TIME_POSITION=")){
            lineOut.remove(0, 18);
            double pos = lineOut.toDouble();
            double avancement = pos/length;
            //qDebug()<<"pos:-"<<avancement<<"-";
            emit(positionNofify(avancement));
        }

        //old -- "Starting playback..."
        //-- "Movie-Aspect is 1.78:1 - prescaling to correct movie aspect." --
        //-- "VO: [xv] 854x480 => 854x480 Planar YV12 " --
        //VO: [xv] 432x324 => 432x324
        else if(lineOut.startsWith("Movie-Aspect is 1")){
            qDebug() << "readLine--"<<lineOut<<"--";
            lineOut.remove(0, 16);
            lineOut.remove(4, 500);
            qDebug() << "aspect"<<lineOut;
            aspect = lineOut.toDouble();
            this->onLaunched();
        }
        //-- "VO: [xv] 854x480 => 854x480 Planar YV12 " --
        //VO: [xv] 432x324 => 432x324
        else if(lineOut.startsWith("VO: [xv] ") && aspect==0){
            qDebug() << "readLine--"<<lineOut<<"--";
            lineOut.remove(0,8);
            int ind = lineOut.indexOf("=");
            lineOut.truncate(ind);
            lineOut = lineOut.trimmed();
             qDebug() << "resolution"<<lineOut;
            ind = lineOut.indexOf("x");
            QString sw = lineOut.left(ind);
            sw = sw.trimmed();
            QString hw = lineOut.mid(ind+1);
            hw = hw.trimmed();
            double h = hw.toDouble();
            double w = sw.toDouble();
            aspect = w/h;
            this->onLaunched();
        }

        //emit(outputLineChanged());
    }
}

void MPlayerWrapper::readyToReadError(){
    QString err = QString(innerProcess->readAllStandardError());
    qDebug()<< "error:" << err;
    emit(failed(err));
}

void MPlayerWrapper::processFinished(int exitCode, QProcess::ExitStatus exitStatus){
    this->refreshTimer->stop();
    this->aspect=0;
    qDebug()<<"finish status:" << exitStatus <<" ,code: " << exitCode;
    if(!nextIdToPlay.isNull()){
       this->playNextVideo();
       qDebug()<<"finish and play ordered vid";
       return;
    }
    emit(videoFinished(exitCode));
}

void MPlayerWrapper::sendOrder(QString line){
    //qDebug() << "write" << line;
    QByteArray cmd;
    cmd.append(line).append("\n");
    innerProcess->write(cmd);
}







